#pragma once
#include <iostream>
#include <string>
#include <iomanip>
#include <unistd.h>
#include <sys/ioctl.h>
#include <limits>
#include <algorithm> // 用于 std::min, std::max

class ProgressBar
{
public:
	ProgressBar(int total, std::string label = "Progress") : _total(total), _label(label)
	{
		// 获取终端宽度，默认 80
		_terminalWidth = 80;
		if (isatty(STDOUT_FILENO))
		{
			struct winsize w;
			if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) == 0)
			{
				_terminalWidth = w.ws_col;
			}
		}
	}

	void update(int progress)
	{
		if (_total > 0)
		{
			progress = std::min(progress, _total); // 防止 progress > _total
			float ratio = static_cast<float>(progress) / _total;
			int barWidth = std::max(
				std::min(_terminalWidth - static_cast<int>(_label.size()) - 15, 50),
				10 // 最小宽度 10
			);
			int numBlocks = static_cast<int>(barWidth * ratio);

			std::cout << _label << ": [";
			for (int i = 0; i < barWidth; ++i)
			{
				if (i < numBlocks)
				{
					std::cout << "=";
				}
				else if (i == numBlocks)
				{
					std::cout << ">";
				}
				else
				{
					std::cout << " ";
				}
			}
			std::cout << "] " << std::fixed << std::setprecision(2) << (ratio * 100) << "%\r" << std::flush;
		}
		else
		{
			std::cout << _label << ": Downloaded " << progress << " bytes\r" << std::flush;
		}
	}

	void Done()
	{
		std::cout << std::endl
				  << "Done!" << std::endl;
	}

private:
	int _total;
	std::string _label;
	int _terminalWidth;
};